import { Monitor } from ".."
import type { BaseBehavior } from "./behavior-type"
import { setupClickMonitor } from "./click-monitor"
// import { setupResourceMonitor } from "./resource-monitor"
import { setupRouteMonitor } from "./route-monitor"

// 创建用户行为类
export class Behavior {
    monitor: InstanceType<typeof Monitor>
    // maxBehaviorCounts 控制上报用户行为的最大条数
    maxBehaviorCounts: number = 20
    stack: any = []
    constructor(monitor: InstanceType<typeof Monitor>, maxCounts?: number) {
        this.monitor = monitor
        if (maxCounts) {
            this.maxBehaviorCounts = maxCounts
        }
        // 调用初始化方法
        this.init()
    }

    // 初始化监听
    init() {
        setupClickMonitor(this)
        setupRouteMonitor(this)
        // setupResourceMonitor(this)
    }

    // 添加用户行为栈
    push(data: any) {
        if (this.stack.length >= this.maxBehaviorCounts) {
            // 超出则删除第一条
            this.stack.shift()
        }
        this.stack.push(data)

        // 按照时间排序
        this.sortByTime()
    }

    // 按时间排序
    private sortByTime(): void {
        this.stack.sort((a: any, b: any) => a.time - b.time)
    }

    // 获取当前行为栈（上报用）
    getStack(): BaseBehavior[] {
        return [...this.stack]
    }

    // 清空行为栈
    clear(): void {
        this.stack = []
    }
}
